package com.itheima.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Map;

/**
 * 根据两地经纬度计算距离，单位/米
 * 驾车路线规划
 */
public class BaiduMapTest2 {
    public static void main(String[] args) throws Exception {
        String ak = "gDtBdcV4ZiKXkhvOWiZ1rggfXOt3xHcy";
        String origin = "28.126828,112.909913";//起点经纬度，格式为：纬度，经度；小数点后不超过6位
        String destination = "28.251818,113.087559";//终点经纬度，格式为：纬度，经度；小数点后不超过6位
        String httpUrl = "https://api.map.baidu.com/directionlite/v1/driving?origin=" + origin + "&destination=" + destination + "&ak=" + ak;

        StringBuilder json = new StringBuilder();

        URL url = new URL(httpUrl);
        URLConnection urlConnection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();
        System.out.println(json.toString());


        String data = json.toString();
        if (data != null && !"".equals(data)) {
            Map map = JSON.parseObject(data, Map.class);
            if ("0".equals(map.getOrDefault("status", "500").toString())) {
                Map childMap = (Map) map.get("result");
                JSONArray jsonArray = (JSONArray) childMap.get("routes");
                //方案距离
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                double distance = Double.parseDouble(jsonObject.get("distance") == null ? "0" : jsonObject.get("distance").toString());
                Integer duration = Integer.parseInt(jsonObject.get("duration") == null ? "0" : jsonObject.get("duration").toString());
                System.out.println(distance/1000);
                System.out.println(duration/60+"分钟");
                System.out.println(duration);
            }
        }


    }
}
